/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.services;

import java.util.Set;
import java.util.Map;
import java.util.List;
import java.util.Locale;
import java.util.HashMap;
import java.util.HashSet;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.security.RolesAllowed;
import org.internna.iwebmvc.dao.DAO;
import org.internna.iwebmvc.model.Sex;
import org.internna.iwebmvc.model.UUID;
import org.internna.iwebmvc.model.User;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebmvc.model.Country;
import org.internna.iwebmvc.dao.SecurityDAO;
import org.internna.iwebmvc.security.UserManager;
import org.internna.iwebmvc.utils.CollectionUtils;
import org.internna.iwebjtracker.model.TrackerUser;
import org.internna.iwebmvc.model.security.RoleImpl;
import org.internna.iwebmvc.model.security.UserImpl;
import org.internna.iwebjtracker.i18n.MessageResolver;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.annotations.RemoteMethod;
import org.springframework.context.MessageSource;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

import static org.internna.iwebmvc.utils.StringUtils.hasText;
import static org.internna.iwebmvc.utils.StringUtils.validateEmail;
import static org.internna.iwebmvc.spring.i18n.WebContextLocale.getActiveLocale;

/**
 * Default implementation that registers users using AJAX.
 *
 * TODO: the trackeruser retrieved from database must be cached
 *
 * @author Jose Noheda
 * @since 1.0
 */
@Transactional
@RemoteProxy(name = "TrackerUserManager")
public final class DefaultTrackerUserManager extends MessageResolver implements TrackerUserManager {

    private DAO dao;
    private SecurityDAO securityDAO;
    private UserManager userManager;
    private final Set<String> themes;
    private String theme = "soria", salt;
    private List<Locale> supportedLocales;

    /**
     * Sets the configured message resolution bean.
     *
     * @param messageSource any
     */
    public DefaultTrackerUserManager(MessageSource messageSource) {
        super(messageSource);
        themes = new HashSet<String>(3);
        themes.add("soria");
        themes.add("tundra");
        themes.add("nihilo");
    }

    /**
     * Spring (REQUIRED) injection point.
     *
     * @param dao a not null implementation
     */
    @Required public void setDao(DAO dao) {
        Assert.notNull(dao);
        this.dao = dao;
    }

    /**
     * Spring (REQUIRED) injection point.
     *
     * @param dao a not null implementation
     */
    @Required public void setSecurityDAO(SecurityDAO securityDAO) {
        Assert.notNull(securityDAO);
        this.securityDAO = securityDAO;
    }

    /**
     * Spring (REQUIRED) injection point.
     *
     * @param dao a not null implementation
     */
    @Required public void setSalt(String salt) {
        Assert.hasText(salt);
        this.salt = salt;
    }

    /**
     * Spring (REQUIRED) injection point.
     *
     * @param dao a not null implementation
     */
    @Required public void setUserManager(UserManager userManager) {
        Assert.notNull(userManager);
        this.userManager = userManager;
    }

    /**
     * Changes default theme for registering users.
     *
     * @param theme any
     */
    public void setTheme(String theme) {
        if (hasText(theme)) {
            this.theme = theme;
        }
    }

    /**
     * Collection of locales supported by the application. If none is specified
     * it falls back to ENGLISH.
     *
     * @param supportedLocales any
     */
    public void setSupportedLocales(List<Locale> supportedLocales) {
        this.supportedLocales = supportedLocales;
    }

    /**
     * Validates username, password and email and creates a user with the configured defaults.
     *
     * @param username any string
     * @param password any string
     * @param email any string
     * @return true if the (tracker) user was saved
     */
    @RemoteMethod
    @Override public String register(String username, String password, String email) {
        if (hasText(username) && hasText(password) && validateEmail(email)) {
            UserImpl user = new UserImpl();
            user.setEmail(email);
            user.setUsername(username);
            user.setName(user.getUsername());
            user.addRole(securityDAO.findAuthority(RoleImpl.ROLE_USER));
            user.addRole(securityDAO.findAuthority(RoleImpl.ROLE_ANONYMOUS));
            try {
                user.setLocale(getLocale());
            } catch (IllegalStateException ex) {
                user.setLocale(Locale.ENGLISH);
            }
            user.setLocale(new Locale(user.getLocale().getCountry()));
            user.setSalt(salt);
            user.setTheme(theme);
            try {
                user.setPassword(password);
            } catch (Exception ex) {
                return ex.getMessage();
            }
            TrackerUser trackerUser = new TrackerUser();
            trackerUser.setSecurityUser(user);
            return register(trackerUser);
        }
        return resolve("ui.registration.errorData");
    }

    private Locale getLocale() {
        Locale locale = getActiveLocale();
        if ((locale != null) && CollectionUtils.isNotEmpty(supportedLocales) && (!supportedLocales.contains(new Locale(locale.getCountry())))) {
            locale = Locale.ENGLISH;
        }
        return locale == null ? new Locale("en") : new Locale(locale.getCountry());
    }

    /**
     * Checks that a user with that username does not exist and creates it.
     *
     * @param user any
     * @return true if the user was created
     */
    @Override public String register(TrackerUser user) {
        if ((user != null) && (user.getSecurityUser() instanceof UserImpl)) {
            UserImpl securityUser = (UserImpl) user.getSecurityUser();
            if ((securityUser != null) && (securityDAO.findUser(securityUser.getUsername()) == null)) {
                securityUser.setEnabled(false);
                securityDAO.createUser(securityUser);
                dao.create(user);
                return null;
            }
            return resolve("ui.registration.userExists");
        }
        return resolve("ui.registration.errorUser");
    }

    /**
     * Changes user current password without affecting the session.
     *
     * @param password any
     * @return the validation error or null
     */
    @RemoteMethod
    @RolesAllowed("ROLE_USER")
    @Override public String changePassword(String password) {
        if (hasText(password)) {
            User user = getCurrentUser();
            if ((user != null) && (!user.isAnonymous())) {
                UserImpl u = (UserImpl) securityDAO.findUser(user.getUsername());
                u.setSalt(salt);
                try {
                    u.setPassword(password);
                } catch (Exception ex) {
                    return ex.getMessage();
                }
                securityDAO.updateUser(u);
            }
            return resolve("ui.profile.security.noUser");
            
        }
        return resolve("ui.profile.security.noPassword");
    }

    /**
     * Obtains the current logged in username and delegates the logic (if not anonymous).
     *
     * @return any
     */
    @Override public TrackerUser getCurrentTrackerUser() {
        User user = userManager.getActiveUser();
        return user != null && !user.isAnonymous() ? getTrackerUser(user.getUsername()) : null;
    }

    /**
     * Gets or creates the tracker user that matches this security username.
     *
     * @param username any
     * @return
     */
    @Override public TrackerUser getTrackerUser(String username) {
        Map<String, Object> params = new HashMap<String, Object>(1);
        params.put("username", username);
        List<TrackerUser> userList = dao.findByNamedQuery(TrackerUser.FIND_BY_USERNAME, 0, 1, params);
        return CollectionUtils.isNotEmpty(userList) ? userList.get(0) : createTrackerUser(username);
    }

    private TrackerUser createTrackerUser(String username) {
        TrackerUser trackerUser = null;
        if (hasText(username)) {
            UserImpl user = (UserImpl) securityDAO.findUser(username);
            if (user != null) {
                trackerUser = new TrackerUser();
                trackerUser.setSecurityUser(user);
                trackerUser.setSex(dao.first(Sex.class));
                dao.create(trackerUser);
            }
        }
        return trackerUser;
    }

    /**
     * Allows changes to the name, sex and country of the current user.
     *
     * @param name any (empty values won't change anything)
     * @param sex any
     * @param country any
     * @param request the current http request (if null it will be inferred)
     */
    @RemoteMethod
    @RolesAllowed("ROLE_USER")
    @Override public void editOfflineInformation(String name, UUID sex, UUID country, HttpServletRequest request) {
        User user = getCurrentUser();
        if ((user != null) && (!user.isAnonymous())) {
            String username = user.getUsername();
            editName(name, username, request);
            editSexAndLocation(sex, country, username);
        }
    }

    private void editName(String name, String username, HttpServletRequest request) {
        if (hasText(name)) {
            UserImpl u = (UserImpl) securityDAO.findUser(username);
            u.setName(name);
            securityDAO.updateUser(u);
            userManager.refresh(request);
        }
    }

    private void editSexAndLocation(UUID sex, UUID country, String username) {
        if ((sex != null) || (country != null)) {
            TrackerUser trackerUser = getTrackerUser(username);
            if (trackerUser != null) {
                trackerUser.setSex(sex == null ? null : dao.find(Sex.class, sex));
                trackerUser.setLocation(country == null ? null : dao.find(Country.class, country));
                dao.update(trackerUser);
            }
        }
    }

    /**
     * Allows changes in the provided email and default theme and locale values.
     *
     * @param email any (only null or valid emails are persisted)
     * @param theme any
     * @param locale any
     * @param request the current http request (if null it will be inferred)
     */
    @RemoteMethod
    @RolesAllowed("ROLE_USER")
    @Override public void editPreferences(String email, String newtheme, String locale, HttpServletRequest request) {
        User user = getCurrentUser();
        if ((user != null) && (!user.isAnonymous())) {
            UserImpl u = (UserImpl) securityDAO.findUser(user.getUsername());
            u.setTheme(validateTheme(newtheme) ? newtheme.toLowerCase(Locale.ENGLISH) : theme);
            u.setEmail(validateEmail(email) ? email : null);
            u.setLocale(locale == null ? null : new Locale(locale));
            securityDAO.updateUser(u);
            userManager.refresh(request);
        }
    }

    /**
     * Checks if theme is any of soria, tundra or nihilo.
     *
     * @param theme any
     * @return fals unless theme in (tundra, nihilo, soria)
     */
    protected boolean validateTheme(String theme) {
        boolean valid = false;
        if (hasText(theme)) {
            valid = themes.contains(theme.toLowerCase(Locale.ENGLISH));
        }
        return valid;
    }

    private User getCurrentUser() {
        try {
            return userManager.getActiveUser();
        } catch (Exception e) {
            return null;
        }
    }

}
